package com.puyuba.puyuba.view.fragment;

import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.flyco.tablayout.SlidingTabLayout;
import com.puyuba.puyuba.MainActivity;
import com.puyuba.puyuba.R;
import com.puyuba.puyuba.bean.DownCardBean;
import com.puyuba.puyuba.network.UserApi;
import com.puyuba.puyuba.view.activity.ChatActivity;
import com.puyuba.puyuba.view.activity.MsgListActivity;
import com.puyuba.puyuba.view.activity.MyUserActivity;
import com.puyuba.puyuba.view.dialog.ContactAdminDialog;
import com.puyuba.puyuba.view.dialog.EducationDemandDialog;
import com.pyb.java.basemodule.BaseFragment;
import com.pyb.java.cache.CacheUserInfo;
import com.puyuba.puyuba.network.BaseApis;
import com.pyb.java.commonutil.ToastHelper;
import com.pyb.java.commonutil.eventbus.EventBusKeys;
import com.pyb.java.commonutil.eventbus.EventBusMessage;

import com.puyuba.puyuba.view.activity.MainWebActivity;
import com.puyuba.puyuba.view.viewpager.WrapViewPager;
import com.pyb.java.commonutil.eventbus.EventBusUtils;
import com.pyb.java.commonutil.utils.StatusBarUtil;
import com.pyb.java.network.ResponseEntity;
import com.pyb.java.network.RetrofitManger;
import com.pyb.java.network.observers.ResponseObserve;
import com.pyb.java.network.scheduler.RxSchedulers;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;

/**
 * 发现页面
 */
public class FindFragment extends BaseFragment {
    private RelativeLayout rlShare;
    private ImageView ivShare;
    private SlidingTabLayout mTabLayout;
    private WrapViewPager mViewPager;
    private String[] mTitles = {"全部需求", "学历需求", "职业需求"};
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private TextView tvUsername;
    private TextView tvCount;
    private RelativeLayout rlAdd;
    private LinearLayout llMyUser;
    private TextView tvMyCount;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_find;
    }

    @Override
    public void initView(View view) {
        View viewStatusBar = (View) view.findViewById(R.id.view_status_bar4);
        int screenHeight = StatusBarUtil.getStatusBarHeight(getContext());
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) viewStatusBar.getLayoutParams();
        layoutParams.height = screenHeight;
        viewStatusBar.setLayoutParams(layoutParams);
        mTabLayout = (SlidingTabLayout) view.findViewById(R.id.tl_1);
        mViewPager = (WrapViewPager) view.findViewById(R.id.vp_home_page);
        rlShare = (RelativeLayout) view.findViewById(R.id.rl_share);
        ivShare = (ImageView) view.findViewById(R.id.iv_share);

        tvUsername = (TextView) view.findViewById(R.id.tv_username);
        tvCount = (TextView) view.findViewById(R.id.tv_count);
        rlAdd = (RelativeLayout) view.findViewById(R.id.rl_add);
        llMyUser = (LinearLayout) view.findViewById(R.id.ll_my_user);
        tvMyCount = (TextView) view.findViewById(R.id.tv_my_count);
        EventBusUtils.register(this);
        getdownloadtimesbyuserid(CacheUserInfo.getInstance().getsUserInfo().getUser().getCrm_user_id());
        initFragments();
        initTab();
        tvUsername.setText("欢迎您：" + CacheUserInfo.getInstance().getsUserInfo().getUser().getUname());
        initListener();
    }

    private void initListener() {
        ivShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //base64加密
//                String url = BaseApis.APPLY_PARTEN_URL + StringUtil.getBase64(Integer.toString(CacheUserInfo.getInstance().getId()));
                MainWebActivity.startMainWebActivity(getContext(), BaseApis.H5_FIND_PARTNER, "申请合伙人");
            }
        });
        llMyUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyUserActivity.startActivity(getContext(), 1);
            }
        });
        rlAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                MainWebActivity.startMainWebActivity(getContext(), BaseApis.TAOCAN, "充值中心");
                initDialog();
            }
        });
    }

    public void initDialog() {
        //去除dialog状态栏
        int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        ContactAdminDialog demandDialog = new ContactAdminDialog(getContext());
        demandDialog.show();
        demandDialog.setText(CacheUserInfo.getInstance().getServiceNum());
        demandDialog.getWindow().getDecorView().setSystemUiVisibility(uiOptions);
    }

    @Subscribe
    public void onMoonEvent(EventBusMessage messageEvent) {
        if (messageEvent.getKey() == EventBusKeys.REFRESH_FIND_LIST) {
            getdownloadtimesbyuserid(CacheUserInfo.getInstance().getsUserInfo().getUser().getCrm_user_id());
            for (int i = 0; i < mFragments.size(); i++) {
                if (i == mViewPager.getCurrentItem()) continue;
                FindTabListFragment findTabListFragment = (FindTabListFragment) mFragments.get(i);
                findTabListFragment.initData();
            }
        }
    }

    /**
     * 获取下载次数
     *
     * @param userid
     */
    private void getdownloadtimesbyuserid(int userid) {
        RetrofitManger.getInstance().createService(UserApi.class)
                .getdownloadtimesbyuserid(userid)
                .compose(RxSchedulers.applySchedulers())
                .subscribe(new ResponseObserve<DownCardBean>() {

                    @Override
                    public void onSuccess(ResponseEntity<DownCardBean> responseEntity) {
                        int downloadtimes = responseEntity.getData().getDownloadtimes();
                        CacheUserInfo.getInstance().saveServiceNumber(downloadtimes);
                        tvCount.setText("服务次数：" + downloadtimes);
                        tvMyCount.setText(responseEntity.getData().getCustomer_total() + "");
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        if (errorMsg != null && !errorMsg.equals("")) {
                            ToastHelper.show(errorMsg);
                        } else {
                            ToastHelper.show("服务器繁忙，请稍后再试");
                        }
                    }

                    @Override
                    public void onSubscribeStart(@io.reactivex.annotations.NonNull Disposable disposable) {
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void initFragments() {
        mFragments.clear();
        mFragments.add(FindTabListFragment.getInstance(-1));
        mFragments.add(FindTabListFragment.getInstance(1));
        mFragments.add(FindTabListFragment.getInstance(2));
    }

    private void initTab() {
        mViewPager.setAdapter(new MyPagerAdapter(getChildFragmentManager()));
        mViewPager.setOffscreenPageLimit(2);
        mTabLayout.setViewPager(mViewPager);
        mTabLayout.setOnTabSelectListener(new com.flyco.tablayout.listener.OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                mViewPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mTabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mViewPager.setCurrentItem(0);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter {
        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTitles[position];
        }


        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBusUtils.unRegister(this);
    }
}
